package service;

import DAO.OrderDaoImpl;
import beans.Order;
import beans.User;
import dbutils.DBHelper;
import utils.DateUtil;
import utils.ValidationUtil;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;

import static dbutils.DBHelper.*;
import static java.sql.DriverManager.getConnection;

public class CustomerService {

    // 检查用户名是否存在
    public static boolean isUsernameExists(String username) {
        Connection conn = DBHelper.getConn();
        PreparedStatement stat = null;
        ResultSet rs = null;
        try {
            String checkNameSql = "SELECT * FROM customer WHERE cname = ?";
            stat = conn.prepareStatement(checkNameSql);
            stat.setString(1, username);
            rs = stat.executeQuery();
            return rs.next();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, stat, rs);
        }
        return false;
    }


    // 检查手机号是否存在
    public static boolean isPhoneExists(String phone) {
        Connection conn = DBHelper.getConn();
        PreparedStatement stat = null;
        ResultSet rs = null;
        try {
            String checkPhoneSql = "SELECT * FROM customer WHERE cphone = ?";
            stat = conn.prepareStatement(checkPhoneSql);
            stat.setString(1, phone);
            rs = stat.executeQuery();
            return rs.next();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, stat, rs);
        }
        return false;
    }


    /*
     * 插入空账号，用于注册
     */
    public void createNewCustomer(User customer) {
        Connection conn = DBHelper.getConn();
        String sql = "INSERT customer (cname,cphone,cpassword,cmoney) VALUE(?,?,?,?);";
        PreparedStatement stat = null;
        ResultSet rs = null;
        try {
            stat = conn.prepareStatement(sql);
            stat.setString(1, customer.getName());
            stat.setString(2, customer.getPhone());
            stat.setString(3, customer.getPassword());
            stat.setString(4, String.valueOf(customer.getMoney()));
            stat.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, stat, rs);
        }
    }


    /*
     * 注册功能
     */
    public void signIn(String name, String phone, String password, String confirmPassword) {
        User customer = new User();
        String customerName = name;
        String customerPhone = phone;
        String customerPassword = ValidationUtil.getPassword(password, confirmPassword);
        customer.setName(customerName);
        customer.setPhone(customerPhone);
        customer.setPassword(customerPassword);
        customer.setMoney(0);
        //新建用户
        createNewCustomer(customer);

        // 更新用户到数据库
        updateCustomer(customer);

        JOptionPane.showMessageDialog(null, "用户：" + customerName + " 注册完成！感谢使用本银行账户。");

        Date time = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
        String dateTimeNow = sdf.format(time);
        LogService.addLogs(customer, "顾客 " + customerName + " 于" + dateTimeNow + "注册系统。");
    }


    //用户名登录
    public User loginN(String name, String password) {
        User customer = findCname(name);
        // 判断账户是否存在，密码是否匹配
        if (customer != null && customer.getPassword().equals(password)) {
            // 登录成功
            JOptionPane.showMessageDialog(null, "登录成功！当前用户为：" + name);
            // 记录登录日志
            LogService.addLogs(customer, "顾客 " + customer.getName() + "登录系统");
            return customer;
        } else {
            // 登录失败，密码错误
            JOptionPane.showMessageDialog(null, "账号或密码错误，请重新输入");
            return null;
        }
    }


    //手机号登录
    public User loginP(String phone, String password) {
        User customer = findCphone(phone);
        // 判断账户是否存在，密码是否匹配
        if (customer != null && customer.getPassword().equals(password)) {
            // 登录成功
            JOptionPane.showMessageDialog(null, "登录成功！当前用户为：" + customer.getName());
            // 记录登录日志
            LogService.addLogs(customer, "顾客 " + customer.getName() + "登录系统");
            return customer;
        } else {
            // 登录失败，密码错误
            JOptionPane.showMessageDialog(null, "账号或密码错误，请重新输入");
            return null;
        }

    }


    /*
     * 根据name查找数据库的账号
     * @param name
     * @return 返回对应name的 customer 对象，如果不存在返回null
     */
    public User findCname(String cname) {
        if (cname == null) {
            return null;
        }
        Connection conn = DBHelper.getConn();
        String sql = "select * from customer WHERE cname = ? ; ";
        PreparedStatement stat = null;
        ResultSet rs = null;
        User customer = new User();
        try {
            stat = conn.prepareStatement(sql);
            stat.setString(1, cname);
            rs = stat.executeQuery();//executeQuery 该方法用来执行查询语句
            while (rs.next()) {
                customer.setId(rs.getInt("cid"));
                customer.setName(rs.getString("cname"));
                customer.setPhone(rs.getString("cphone"));
                customer.setPassword(rs.getString("cpassword"));
                customer.setMoney(rs.getDouble("cmoney"));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, stat, rs);
        }
        if (customer.getId() == 0) {
            return null;
        } else {
            return customer;
        }
    }


    /*
     * 根据phone查找数据库的账号
     * @param phone
     * @return 返回对应phone的 customer 对象，如果不存在返回null
     */
    public User findCphone(String cname) {
        if (cname == null) {
            return null;
        }
        Connection conn = DBHelper.getConn();
        String sql = "select * from customer WHERE cphone = ? ; ";
        PreparedStatement stat = null;
        ResultSet rs = null;
        User customer = new User();
        try {
            stat = conn.prepareStatement(sql);
            stat.setString(1, cname);
            rs = stat.executeQuery();//executeQuery 该方法用来执行查询语句
            while (rs.next()) {
                customer.setId(rs.getInt("cid"));
                customer.setName(rs.getString("cname"));
                customer.setPhone(rs.getString("cphone"));
                customer.setPassword(rs.getString("cpassword"));
                customer.setMoney(rs.getDouble("cmoney"));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, stat, rs);
        }
        if (customer.getId() == 0) {
            return null;
        } else {
            return customer;
        }
    }


    /*
     * 更新指定 customer 的所有数据
     * @param customer 已设定好数据的 customer 对象
     */
    public void updateCustomer(User customer) {
        Connection conn = DBHelper.getConn();
        String sql = "UPDATE customer SET cname = ?,cphone = ?,cpassword = ?,cmoney = ? WHERE cid = ?";
        PreparedStatement stat = null;
        ResultSet rs = null;

        try {
            stat = conn.prepareStatement(sql);
            stat.setString(1, customer.getName());
            stat.setString(2, customer.getPassword());
            stat.setString(3, customer.getPhone());
            stat.setDouble(4, customer.getMoney());
            stat.setInt(5, customer.getId());
            stat.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, stat, rs);
        }
    }


    // 修改密码
    public void updatePassword(User customer, String oldPassword, String newPassword) {
        // 首先进行参数有效性检查
        if (newPassword.isEmpty()) {
            JOptionPane.showMessageDialog(null, "新密码不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        if (oldPassword.equals(newPassword)) {
            JOptionPane.showMessageDialog(null, "新密码不能和旧密码相同！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        Connection conn = DBHelper.getConn();
        String sql = "SELECT * FROM customer WHERE cid = ? AND cpassword = ?";
        PreparedStatement selectStat = null;
        String updateSql = "UPDATE customer SET cpassword = ? WHERE cid = ?";
        PreparedStatement updateStat = null;

        try {
            // 验证旧密码是否正确
            selectStat = conn.prepareStatement(sql);
            selectStat.setInt(1, customer.getId());
            selectStat.setString(2, oldPassword);
            ResultSet resultSet = selectStat.executeQuery();

            if (resultSet.next()) {
                // 更新密码
                updateStat = conn.prepareStatement(updateSql);
                updateStat.setString(1, newPassword);
                updateStat.setInt(2, customer.getId());
                int rowsAffected = updateStat.executeUpdate();

                if (rowsAffected > 0) {
                    JOptionPane.showMessageDialog(null, "密码修改成功！");
                    LogService.addLogs(customer, "顾客 " + customer.getName() + " 修改了密码");
                } else {
                    JOptionPane.showMessageDialog(null, "密码修改失败！", "错误", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(null, "旧密码错误！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, selectStat, null);
            DBHelper.closeAll(conn, updateStat, null);
        }
    }


    // 充值
    public void rechargeBalance(User customer, double amount) {
        Connection conn = DBHelper.getConn();
        String sql = "UPDATE customer SET cmoney = cmoney + ? WHERE cid = ?";
        PreparedStatement stat = null;

        try {
            stat = conn.prepareStatement(sql);
            stat.setDouble(1, amount);
            stat.setInt(2, customer.getId());
            int rowsAffected = stat.executeUpdate();

            if (rowsAffected > 0) {
                JOptionPane.showMessageDialog(null, "充值成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
                LogService.addLogs(customer, "顾客 " + customer.getName() + "充值金额：" + amount + " 成功");
            } else {
                JOptionPane.showMessageDialog(null, "充值失败！", "提示", JOptionPane.ERROR_MESSAGE);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, stat, null);
        }
    }

    //商品展示
    public JTable createJTable() {
        // 创建表头
        String[] columnNames = {"ID", "商品", "数量", "价格", "尺码", "商家", "生产商", "状态"};

        // 创建 JTable 对象
        JTable table = new JTable();

        // 设置表头
        DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
        tableModel.setColumnIdentifiers(columnNames);

        // 查询数据库数据并添加到表格中
        Connection conn = DBHelper.getConn();
        String sql = "SELECT * FROM shoe";
        PreparedStatement selectStat = null;
        ResultSet resultSet = null;

        try {
            selectStat = conn.prepareStatement(sql);
            resultSet = selectStat.executeQuery();

            while (resultSet.next()) {
                int id = resultSet.getInt("sid");
                String name = resultSet.getString("sname");
                int quantity = resultSet.getInt("scount");
                double price = resultSet.getDouble("sprice");
                String size = resultSet.getString("ssize");
                String merchant = resultSet.getString("smerchant");
                String producer = resultSet.getString("sproducer");
                String status = resultSet.getString("sstatus");

                // 添加数据行
                Object[] rowData = {id, name, quantity, price, size, merchant, producer, status};
                tableModel.addRow(rowData);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, selectStat, resultSet);
        }

        return table;
    }


    //商品购买
    public void performPurchase(JTable table, User customer) {
        int selectedRow = table.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(null, "请先选择一行商品！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        int id = (int) table.getValueAt(selectedRow, table.getColumn("ID").getModelIndex());

        int quantity = (int) table.getValueAt(selectedRow, table.getColumn("数量").getModelIndex());

        double balance = customer.getMoney();

        //判断商品是否下架
        if ("已下架".equals(table.getValueAt(selectedRow, table.getColumn("状态").getModelIndex()).toString())) {
            JOptionPane.showMessageDialog(null, "该商品已下架，请购买其他商品");
            return;
        }

        //判断商品非已下架后判断状态是否为已上架，否则提示出错
        if (!"已上架".equals(table.getValueAt(selectedRow, table.getColumn("状态").getModelIndex()).toString())) {
            JOptionPane.showMessageDialog(null, "该商品状态出错，请购买其他商品");
            return;
        }

        String input = JOptionPane.showInputDialog(null, "请输入购买数量：", "购买商品", JOptionPane.PLAIN_MESSAGE);
        if (input == null || input.isEmpty()) {
            JOptionPane.showMessageDialog(null, "购买操作已取消！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        int purchaseQuantity;
        try {
            purchaseQuantity = Integer.parseInt(input);
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null, "请输入有效的购买数量！", "提示", JOptionPane.ERROR_MESSAGE);
            return;
        }

        if (purchaseQuantity <= 0) {
            JOptionPane.showMessageDialog(null, "请输入有效的购买数量！", "提示", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (purchaseQuantity > quantity) {
            JOptionPane.showMessageDialog(null, "购买量超出库存量，请重新输入购买量！", "提示", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if (quantity <= 3) {
            JOptionPane.showMessageDialog(null, "库存不足，请购买其他商品", "提示", JOptionPane.ERROR_MESSAGE);
            return;
        }

        Double price = (double) 0;
        Object value = table.getValueAt(selectedRow, table.getColumn("价格").getModelIndex());
        if (value instanceof Float) {
            price = ((Float) value).doubleValue();
        } else if (value instanceof Double) {  // 添加对价格类型为 Double 的处理
            price = (Double) value;
        } else {
            JOptionPane.showMessageDialog(null, "价格无效！", "提示", JOptionPane.ERROR_MESSAGE);
            return;
        }

        double totalPrice = price * purchaseQuantity;
        if (balance < totalPrice) {
            JOptionPane.showMessageDialog(null, "余额不足，购买失败！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        //更新用户余额
        balance -= totalPrice;
        customer.setMoney(balance);
        updateCustomer(customer);

        //更新商家余额
        String producer = table.getValueAt(selectedRow, table.getColumn("商家").getModelIndex()).toString();
        updateProducerBalance(producer, totalPrice);

        //更新商品数量
        int scount = quantity - purchaseQuantity;
        updateQuantityInDatabase(id, scount);

        JOptionPane.showMessageDialog(null, "购买成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
        refreshProductData(table);

        String name = table.getValueAt(selectedRow, table.getColumn("商品").getModelIndex()).toString();
        String merchant = table.getValueAt(selectedRow, table.getColumn("商家").getModelIndex()).toString();
        new OrderService().addcOrderService(customer, name, String.valueOf(price), merchant, producer);
        LogService.addLogs(customer, "顾客 " + customer.getName() + "购买了商品：" + name);
    }


    //购买后商品的数量
    private void updateQuantityInDatabase(int sId, int scount) {
        // 执行更新商品数量的数据库操作
        Connection conn = DBHelper.getConn();
        String sql = "UPDATE shoe SET scount = ? WHERE sid = ?";
        PreparedStatement updateStat = null;

        try {
            updateStat = conn.prepareStatement(sql);
            updateStat.setInt(1, scount);
            updateStat.setInt(2, sId);
            updateStat.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, updateStat, null);
        }
    }


    //购买后商家的余额
    public void updateProducerBalance(String producer, double balance) {
        Connection conn = DBHelper.getConn();
        String sql = "UPDATE merchant SET mmoney = mmoney + ? WHERE mname = ?";
        PreparedStatement updateStat = null;

        try {
            updateStat = conn.prepareStatement(sql);
            updateStat.setDouble(1, balance);
            updateStat.setString(2, producer);
            updateStat.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, updateStat, null);
        }
    }


    // 刷新商品并自动下架数量小于等于3的商品
    public void refreshProductData(JTable table) {
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        model.setRowCount(0);  // 清空表格

        try (Connection conn = getConnection(URL, DBUser, DBPassword);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM shoe")) {

            while (rs.next()) {
                Object[] rowData = new Object[8];
                rowData[0] = rs.getInt("sid");
                rowData[1] = rs.getString("sname");
                rowData[2] = rs.getInt("scount");
                rowData[3] = rs.getDouble("sprice");
                rowData[4] = rs.getString("ssize");
                rowData[5] = rs.getString("smerchant");
                rowData[6] = rs.getString("sproducer");

                int scount = rs.getInt("scount");
                String sstatus = rs.getString("sstatus");

                // 检查是否需要自动下架
                if (scount <= 3 && sstatus.equals("已上架")) {
                    sstatus = "已下架";
                    updateStatusInDatabase(rs.getInt("sid"), sstatus); // 更新数据库中的状态
                }

                rowData[7] = sstatus;

                model.addRow(rowData);
            }

            // 刷新表格
            model.fireTableDataChanged();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    // 更新商品状态到数据库
    private void updateStatusInDatabase(int sid, String sstatus) {
        try (Connection conn = getConnection(URL, DBUser, DBPassword);
             PreparedStatement stmt = conn.prepareStatement("UPDATE shoe SET sstatus = ? WHERE sid = ?")) {

            stmt.setString(1, sstatus);
            stmt.setInt(2, sid);

            stmt.executeUpdate();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }


    //查询商品
    public void searchTable(JTable table, String keyword) {
        // 清空表格数据
        DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
        tableModel.setRowCount(0);

        // 查询数据库数据并添加到表格中
        Connection conn = DBHelper.getConn();
        String sql = "SELECT * FROM shoe WHERE sname LIKE ?";
        PreparedStatement selectStat = null;
        ResultSet resultSet = null;

        try {
            selectStat = conn.prepareStatement(sql);
            selectStat.setString(1, "%" + keyword + "%");
            resultSet = selectStat.executeQuery();

            while (resultSet.next()) {
                Object[] rowData = new Object[8];
                rowData[0] = resultSet.getInt("sid");
                rowData[1] = resultSet.getString("sname");
                rowData[2] = resultSet.getInt("scount");
                rowData[3] = resultSet.getDouble("sprice");
                rowData[4] = resultSet.getString("ssize");
                rowData[5] = resultSet.getString("smerchant");
                rowData[6] = resultSet.getString("sproducer");
                rowData[7] = resultSet.getString("sstatus");

                // 添加数据行
                tableModel.addRow(rowData);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, selectStat, resultSet);
        }
    }


    //查询订单
    public void showOrderData(JTable table, User customer) {
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        model.setRowCount(0);  // 清空表格

        try (Connection conn = getConnection(URL, DBUser, DBPassword);
             Statement stmt = conn.createStatement();
             PreparedStatement ps = null;
             ResultSet rs = stmt.executeQuery("SELECT * FROM corders where user = '" + customer.getName() + "';")) {

            while (rs.next()) {
                Object[] rowData = new Object[7];
                rowData[0] = rs.getString("orderNum");
                rowData[1] = rs.getString("user");
                rowData[2] = rs.getString("times");
                rowData[3] = rs.getString("name");
                rowData[4] = rs.getString("price");
                rowData[5] = rs.getString("merchant");
                rowData[6] = rs.getString("producer");

                model.addRow(rowData);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }


    // 退货
    public void ReturnService(JTable table, User customer) {
        int selectedRow = table.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(null, "请先选择一行商品！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        // 获取订单信息
        int num = Integer.parseInt(table.getValueAt(selectedRow, table.getColumn("订单编号").getModelIndex()).toString());
        String name = table.getValueAt(selectedRow, table.getColumn("商品名称").getModelIndex()).toString();
        String merchant = table.getValueAt(selectedRow, table.getColumn("商家").getModelIndex()).toString();

        // 检查订单是否已退货或换货
        if (name.contains("(未退货)")) {
            JOptionPane.showMessageDialog(null, "该订单已退货或换货，不能重复退货！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        // 修改订单信息
        boolean isSuccess = updateOrder1(name,num);

        if (isSuccess) {
            // 在商品名称后面添加未退货的标记
            table.setValueAt(name + "(未退货)", selectedRow, table.getColumn("商品名称").getModelIndex());

            LogService.addLogs(customer, "顾客 " + customer.getName() + " 发送了退货货 " + name + " 给商家 " + merchant);
            JOptionPane.showMessageDialog(null, "发送退货申请成功");
        } else {
            JOptionPane.showMessageDialog(null, "更新订单信息失败！", "提示", JOptionPane.ERROR_MESSAGE);
        }
    }

    public boolean updateOrder1(String name,int num) {
        // 创建数据库连接
        Connection conn = null;
        PreparedStatement stmt = null;
        boolean isSuccess = false;

        try {
            // 建立数据库连接
            conn = getConnection(URL, DBUser, DBPassword);

            // 构建更新语句
            String sql = "UPDATE corders SET name = ? WHERE name = ? AND  orderNum = ?";

            // 创建PreparedStatement对象
            stmt = conn.prepareStatement(sql);

            // 设置更新参数
            stmt.setString(1, name + "(未退货)");
            stmt.setString(2, name);
            stmt.setInt(3, num);

            // 执行更新操作
            int rowsAffected = stmt.executeUpdate();

            // 判断更新是否成功
            if (rowsAffected > 0) {
                isSuccess = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, stmt, null);
        }

        return isSuccess;
    }



    // 换货
    public void ReplacementService(JTable table, User customer) {
        int selectedRow = table.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(null, "请先选择一行商品！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        // 获取订单信息
        int num = Integer.parseInt(table.getValueAt(selectedRow, table.getColumn("订单编号").getModelIndex()).toString());
        String name = table.getValueAt(selectedRow, table.getColumn("商品名称").getModelIndex()).toString();
        String merchant = table.getValueAt(selectedRow, table.getColumn("商家").getModelIndex()).toString();

        // 检查订单是否已退货或换货
        if (name.contains("(未退货)") || name.contains("(未换货)")) {
            JOptionPane.showMessageDialog(null, "该订单已退货或换货，不能重复换货！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }



        // 检查订单是否已退货或换货
        if (name.contains("(未换货)")) {
            JOptionPane.showMessageDialog(null, "该订单已退货或换货，不能重复退货！", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        // 修改订单信息
        boolean isSuccess = updateOrder2(name,num);

        if (isSuccess) {
            // 在商品名称后面添加未退货的标记
            table.setValueAt(name + "(未换货)", selectedRow, table.getColumn("商品名称").getModelIndex());

            LogService.addLogs(customer, "顾客 " + customer.getName() + " 发送了换货 " + name + " 给商家 " + merchant);
            JOptionPane.showMessageDialog(null, "发送换货申请成功");
        } else {
            JOptionPane.showMessageDialog(null, "更新订单信息失败！", "提示", JOptionPane.ERROR_MESSAGE);
        }
    }

    public boolean updateOrder2(String name,int num) {
        // 创建数据库连接
        Connection conn = null;
        PreparedStatement stmt = null;
        boolean isSuccess = false;

        try {
            // 建立数据库连接
            conn = getConnection(URL, DBUser, DBPassword);

            // 构建更新语句
            String sql = "UPDATE corders SET name = ? WHERE name = ? AND  orderNum = ?";

            // 创建PreparedStatement对象
            stmt = conn.prepareStatement(sql);

            // 设置更新参数
            stmt.setString(1, name + "(未换货)");
            stmt.setString(2, name);
            stmt.setInt(3, num);

            // 执行更新操作
            int rowsAffected = stmt.executeUpdate();

            // 判断更新是否成功
            if (rowsAffected > 0) {
                isSuccess = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, stmt, null);
        }

        return isSuccess;
    }




    // 刷新订单
    public JTable refreshOrderData(JTable table, User customer) {
        // 创建表头
        String[] columnNames = {"订单编号", "用户", "下单时间", "商品名称", "商品价格", "商家", "生产商"};

        // 设置表头
        DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
        tableModel.setColumnIdentifiers(columnNames);

        // 查询数据库数据并添加到表格中
        Connection conn = DBHelper.getConn();
        String sql = "SELECT * FROM corders where user = ?";
        PreparedStatement selectStat = null;
        ResultSet resultSet = null;

        try {
            selectStat = conn.prepareStatement(sql);
            selectStat.setString(1, customer.getName());
            resultSet = selectStat.executeQuery();

            while (resultSet.next()) {
                Object[] rowData = new Object[7];
                rowData[0] = resultSet.getInt("orderNum");
                rowData[1] = resultSet.getString("user");
                rowData[2] = resultSet.getString("times");
                rowData[3] = resultSet.getString("name");
                rowData[4] = resultSet.getString("price");
                rowData[5] = resultSet.getString("merchant");
                rowData[6] = resultSet.getString("producer");

                // 添加数据行
                tableModel.addRow(rowData);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, selectStat, resultSet);
        }

        return table;
    }


    //查询日志
    public void showLogData(JTable table, User customer) {
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        model.setRowCount(0);  // 清空表格

        try (Connection conn = getConnection(URL, DBUser, DBPassword);
             PreparedStatement ps = conn.prepareStatement("SELECT * FROM logs WHERE userName = ?");
        ) {

            ps.setString(1, customer.getName());

            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    Object[] rowData = new Object[3];
                    rowData[0] = rs.getString("userName");
                    rowData[1] = rs.getString("times");
                    rowData[2] = rs.getString("logContext");

                    model.addRow(rowData);
                }
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }


    // 刷新日志
    public JTable refreshLogData(JTable table, User customer) {
        // 创建表头
        String[] columnNames = {"用户名", "时间", "日志内容"};

        // 设置表头
        DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
        tableModel.setColumnIdentifiers(columnNames);

        // 查询数据库数据并添加到表格中
        Connection conn = DBHelper.getConn();
        String sql = "SELECT * FROM logs where userName = ?";
        PreparedStatement selectStat = null;
        ResultSet resultSet = null;

        try {
            selectStat = conn.prepareStatement(sql);
            selectStat.setString(1, customer.getName());
            resultSet = selectStat.executeQuery();

            while (resultSet.next()) {
                Object[] rowData = new Object[3];
                rowData[0] = resultSet.getString("userName");
                rowData[1] = resultSet.getString("times");
                rowData[2] = resultSet.getString("logContext");

                // 添加数据行
                tableModel.addRow(rowData);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBHelper.closeAll(conn, selectStat, resultSet);
        }

        return table;
    }


    /*
     * 登出功能
     */
    public void Logout(User user_Login) {
        Date time = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
        String dataTimeNow = sdf.format(time);
        //记录登出系统时间
        LogService.addLogs(user_Login, user_Login.getName() + " 于" + dataTimeNow + "  登出系统。");
        JOptionPane.showMessageDialog(null, user_Login.getName() + " 顾客于" + dataTimeNow + "  登出系统。");
        //将当前登出清除
        user_Login = null;
    }
}
